package admin

import (
	"beegoProject/models"
	"beegoProject/utils/errmsg"
	"encoding/json"
	"github.com/astaxie/beego"
)

type ArticleController struct {
	beego.Controller
}

//添加文章
// @router /admin/article/add [post]
func (this *ArticleController) AddArtcile() {
	var article models.Article

	body := this.Ctx.Input.RequestBody
	//绑定到Article模型
	_ = json.Unmarshal(body, &article)

	//存入数据库
	code := models.CreateArticle(&article)


	result := map[string]interface{}{
		"status":  code,
		"data":    article,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}


//编辑文章
// @router /admin/article/:id [put]
func (this *ArticleController) EditArticle() {
	var data models.Article

	id, _ := this.GetInt(":id")

	body := this.Ctx.Input.RequestBody
	//绑定到Article模型
	_ = json.Unmarshal(body, &data)

	code := models.EditArticle(id, &data)

	result := map[string]interface{}{
		"status":  code,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}



//获取单个文章
// @router /article/:id [get]
func (this *ArticleController) GetArtcile() {
	id, _ := this.GetInt(":id")
	data, code := models.GetOneArticle(id)

	result := map[string]interface{}{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}



//获取文章列表
// @router /articles [get]
func (this *ArticleController) GetArtciles() {
	keywords := this.GetString("keywords")
	pageSize, err := this.GetInt("pagesize")
	if pageSize < 1 || err != nil{
		pageSize = 5
	}
	pageNum, err := this.GetInt("pagenum")
	if pageNum < 1 || err != nil{
		pageNum = 1
	}

	data, code, total := models.GetArticles(keywords, pageSize, pageNum, "")

	result := map[string]interface{}{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}



//查询分类下所有文章
// @router /category/:id/artlist [get]
func (this *ArticleController) GetCateArt() {
	id, _ := this.GetInt(":id")
	pageSize, err := this.GetInt("pagesize")
	if pageSize < 1 || err != nil{
		pageSize = 5
	}
	pageNum, err := this.GetInt("pagenum")
	if pageNum < 1 || err != nil{
		pageNum = 1
	}

	data, code, total := models.GetCateArt(id, pageSize, pageNum)
	result := map[string]interface{}{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}



//删除文章
// @router /admin/artdelete/:id [delete]
func (this *ArticleController) DeleteArticle() {
	id, _ := this.GetInt(":id")

	code := models.DeleteArticle(id)

	result := map[string]interface{}{
		"status":  code,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}
